package com.hunter.tools;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.database.bean.WebsitsJob;
import com.hunter.jobs.WebMagicJob;

public class QuartzHunterJob {
	private static final Logger log = Logger.getLogger(QuartzHunterJob.class);
	
	public void start()
	{
		log.info("\n-----------------------------\nINFO:hunter started...\n-----------------------------\n");
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler=null;
		try {
			scheduler = schedulerFactory.getScheduler();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ReadSitesFromXML rsfx=new ReadSitesFromXML();
		List<WebsitsJob> websits=rsfx.getWebsites();
		
		for(WebsitsJob websitsjob:websits)
		{
			JobDataMap newJobDataMap=new JobDataMap();
			newJobDataMap.put("sitebean", websitsjob);
	        JobDetail jobDetail = JobBuilder.newJob()
	                .ofType(WebMagicJob.class)
	                .usingJobData(newJobDataMap)
	                .withIdentity("hunter"+websitsjob.getId(),"hunterGroup")
	                .build();

	        Trigger trigger = TriggerBuilder.newTrigger()
	                .withSchedule(CronScheduleBuilder.cronSchedule(websitsjob.getTask_cron()))
	                .forJob("hunter"+websitsjob.getId(),"hunterGroup")
	                .build();

	        try {
				scheduler.scheduleJob(jobDetail,trigger);		
				scheduler.start();
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		}	

	}

}
